package cn.zxl.spring.holiday.job.shiro;

import cn.zxl.spring.holiday.job.domain.Employee;
import cn.zxl.spring.holiday.job.domain.Role;
import cn.zxl.spring.holiday.job.service.EmployeeService;
import cn.zxl.spring.holiday.job.service.PermissionService;
import cn.zxl.spring.holiday.job.service.RoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Date 2021/10/1 17:38
 * @Version 1.0
 * @Description
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (employee.getAdmin()) {
            List<Role> roles = roleService.list(null);
            for (Role role : roles) {
                info.addRole(role.getSn());
            }
            info.addStringPermission("*:*");
            return info;
        }
        List<String> roles = roleService.findRolesByEid(employee.getId());
        List<String> permissions = permissionService.findPermissionsByEid(employee.getId());
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        Employee employee = employeeService.findByUsername(username);
        if (employee == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getSlat()),getName());
    }
}
